<template>
  <Dialog
    width="910px"
    :title= "id ? '修改商家信息': '新增商家'"
    :visible.sync="innerVisible">

    <el-row>
      <el-col :span="24">
        <el-form class="el-form-col" :model="model" label-position="left" ref="elForm" label-width="120px">
          <Portlet title="商家信息">
            <el-row :gutter="15" class="row">

              <el-col :span="12">
                <el-form-item label="商家名称:" prop="name" :rules="[
                    {required: true, message: '商家名称必须', trigger: 'blur'}
                  ]">
                  <el-input v-model="model.name"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="商家联系人:" prop="prin" :rules="[
                  ]">
                  <el-input v-model="model.prin"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="商家联系电话:" label-width="120px" prop="phone" :rules="[
                    {validator: isPhone, message: '电话格式不正确', trigger: 'blur'},
                  ]">
                  <el-input v-model="model.phone"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </Portlet>

          <Portlet title="分配账号">
            <div slot="header">
              <span>分配账号</span>
              <span style="padding-left:10px; font-size: 14px; color: red;">可分配商家账号,商家可登陆系统查看该商家的订单信息</span>
            </div>
            <el-row :gutter="15">
              <el-col :span="12">
                <el-form-item prop="storageUserId" label="账号姓名:">
                  <el-select
                    v-model="model.storageUserId"
                    filterable
                    clearable
                    placeholder="请输入关键词"
                    remote
                    :remote-method="remoteQuery2"
                    :loading="userLoading">
                    <el-option
                      v-for="item in userArr"
                      :key="item.value"
                      :label="item.text"
                      :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label-width="120px" label="绑定登录手机号:">
                  <el-input :disabled="true" :value="userPhone"></el-input>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label-width="120px" label="角色:">
                  <el-input :disabled="true" :value="getPosition"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </Portlet>

        </el-form>
      </el-col>
    </el-row>

    <div slot="footer">
      <el-button @click="innerVisible = false">关闭窗口</el-button>
      <el-button type="primary" :loading="loading" @click="submit">保存</el-button>
    </div>

  </Dialog>
</template>
<script>
import {dotData, copy, alert, confirm} from '@/utils'
import {isPhoneOrTel, isPhone} from '@/utils/validate'
import {httpSuccessPost, httpGetResponse} from '@/utils/ajax'
import L from 'lodash'

export default {
  props: {
    datas: {
      type: Object,
      default() {
        return {}
      }
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    visible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      if (val) {
        // 重置表单
        this.resetFields()
        // 初始化
        this.$nextTick(_ => { // 解决重置先被执行的问题
          this.id = this.datas.id
          this.initData()
        })
      }
      this.innerVisible = val
    },
    // 如果内部有新值变化，更新外部visible
    innerVisible(val, oldVal) {
      if (val === oldVal) {
        return
      }
      this.$emit('update:visible', val)
    }
  },
  data() {
    return {
      innerVisible: this.visible,
      id: this.datas.id,
      routeName: this.$route.name,
      loading: false,
      cargoOwnerLoading: false,
      userLoading: false,
      productionSelectModalVisible: false, // 产品选择弹窗默认关闭
      model: {
        name: '',
        compayId: '',
        prin: '',
        phone: '',
        storageUserId: '' // 新增 账号id
      },
      userIdMap: new Map(), // 新建storageUserId map
      userArr: [], // 模糊搜索到的 账号数组
      cargoOwnerArr: []
    }
  },
  computed: {
    // 获取storageUserIdMap对象里面的phone
    userPhone() {
      let temp = this.userIdMap.get(this.model.storageUserId)
      if (temp) {
        return dotData(temp, 'phone')
      }
      return ''
    },
    // 获取Map对象里面的 职位--渲染页面用
    getPosition() {
      let temp = this.userIdMap.get(this.model.storageUserId)
      if (temp) {
        return dotData(temp, 'position')
      }
      return ''
    },
    title() { return '修改商家信息' }
  },
  methods: {
    isPhoneOrTel,
    isPhone,
    httpPost(url) {
      let data = copy(this.model, true)
      if (this.id) {
        data.id = this.id
      }
      return httpSuccessPost(url, data).then(response => {
        return response
      })
    },
    initData() {
      if (this.id) {
        this.model.name = this.datas.name
        this.model.compayId = this.datas.compayId
        this.model.prin = this.datas.prin
        this.model.phone = this.datas.phone
        this.model.storageUserId = this.datas.storageUserId
        // 根据详情数据 回填 账号信息
        if (this.model.storageUserId) {
          this.userArr = [
            {
              value: this.model.storageUserId,
              text: this.datas.userName
            }
          ]
          // 回填map
          this.userIdMap.set(this.model.storageUserId, {
            phone: this.datas.userPhone,
            position: this.datas.roleName
          })
        }
      } else {
        // 公司信息
        httpGetResponse('/ms-warehouse-order/basicData/findMyCompanyInfo').then(response => {
          console.log(response, 'response')
          const success = dotData(response, 'success')
          if (success) {
            const data = dotData(response, 'data')
            this.model.compayId = data.id
            this.companyName = data.name
          }
        })
      }
    },
    // 模糊搜索 账号名 userArr
    remoteQuery2(query) {
      this.userLoading = true
      this.remoteMethod2(query, this)
    },
    remoteMethod2: L.debounce((query, _this) => {
      if (!query) {
        _this.userLoading = false
        return
      }
      httpGetResponse('/ms-warehouse-order/user/findStorageUserList', {
        name: query,
        queryStatus: 2
      }).then(response => {
        const success = dotData(response, 'success')
        if (success) {
          let data = dotData(response, 'data')
          let tempArr = []
          if (Array.isArray(data)) {
            _this.userIdMap.clear() // 清空Map
            data.forEach((v, k) => {
              tempArr.push({
                text: v.name,
                value: v.id
              })
              _this.userIdMap.set(v.id, {phone: v.phone, position: v.roleName}) // 初始化Map对象 和它里面应有的属性
            })
          }
          _this.userArr = tempArr
        }
      }).finally(_ => {
        _this.userLoading = false
      })
    }, 1000),
    submit() {
      this.$refs.elForm.validate(result => {
        if (!result) {
          alert('验证未通过')
          return
        }
        this.loading = true
        let title = this.id ? '修改成功' : '新增成功'
        let url = '/ms-warehouse-order/basicData/saveOrUpdateCargoOwner'
        this.httpPost(url).then(response => {
          const success = dotData(response, 'success')
          const id = dotData(response, 'data.id')
          if (success) {
            if (this.id) {
              this.resetFields()
              alert(title, '', 'success')
              this.loading = false
              this.innerVisible = false
              this.$emit('refresh', true)
            } else {
              confirm(title, '是否需要添加厂家产品?', {
                type: 'success',
                showCancelButton: !this.id,
                closeOnClickModal: false
              }).then(_ => {
                this.$router.push({path: '/ss-oms/basic-data/owner/edit/' + id})
              }).catch(_ => {
                this.resetFields()
                this.loading = false
                this.innerVisible = false
                this.$emit('refresh', true)
              }).finally(_ => {
                this.resetFields()
                this.loading = false
                this.innerVisible = false
                this.$emit('refresh', true)
              })
            }
          } else {
            this.loading = false
          }
        }).catch(_ => {
          this.loading = false
        })
      })
    },
    // 清空表格
    resetFields() {
      const elForm = this.$refs.elForm
      if (elForm) {
        this.$refs.elForm.resetFields()
      }
      this.userIdMap.clear()
      this.userArr = []
      this.cargoOwnerArr = []
    }
  }
}
</script>
